package cn.juc;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * unsafe 的cas操作
 */
public class UnsafeLock {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field safe = Unsafe.class.getDeclaredField("theUnsafe");
        safe.setAccessible(true);
        Unsafe unsafe = (Unsafe) safe.get(null);
        long id = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
        long name = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
        //cas
        Student student=new Student();
        unsafe.compareAndSwapInt(student,id,0,1);
        unsafe.compareAndSwapObject(student,name,null,"hahh");
        System.out.println(student.id);
        System.out.println(student.name);

    }

    static class Student{
        private volatile int id;
        private volatile String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }


    }
}
